import KoaRouter from 'koa-router'
import { Models } from '@/common/typings/modle'

import { command } from '@/server/mysql'
import { Success } from '@/core/HttpException'
import { format } from '@/common/utils/date'
import Config from '@/config/Config'

import validator from '@/middlewares/validator'
import schema from '@/common/api-json-schema/system/auth/loginOrRegister'
import { Account } from '@/common/typings/account'
import { saveToken } from '@/server/redis'
import { getToken } from '@/api/v1/system/auth/login'

const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/auth`,
})

router.post('/loginOrRegister', validator(schema, 'body'), async (ctx: Models.Ctx) => {
  const { userName, verifyCode } = ctx.request.body as any
  const date = format(new Date())
  const res: Models.Result = await command(`SELECT * FROM system_user WHERE mobile = '${userName}';`)
  if ((res.results as Account.User[]).length > 0) {
    const user = res.results[0]
    const token = getToken(user, user.password)
    await saveToken(token, JSON.stringify({ id: user.id, userName: user.userName }))
    throw new Success({ data: token })
  } else {
    await command(`
    INSERT INTO system_user ( user_name, mobile, password, created_at, updated_at)
    VALUES
    ( '${userName}', '${userName}', '123456', '${date}', '${date}' );`)
    // 新增的id：insertId
    throw new Success()
  }
})
export default router
